import { useStore } from "@/stores";
import { setChatList, playVoice } from "@/static/ts/common";

// 处理群组消息
export async function handleGroupMessage(data: any) {
  console.log("处理群组消息：", data);
  let store = useStore();
  const { GroupId, MessageId, Grade } = data;
  data.chatId = GroupId;

  try {
    // 获取好友列表
    const lastMessage = await getLastGroupMessage(GroupId);
    playVoice(3);

    if (
      (lastMessage && lastMessage.MessageId + 1 === MessageId) ||
      MessageId == 1 ||
      Grade == 2
    ) {
      // 消息ID连贯，保存消息到数据库
      await store.db.saveData("groupChat", [
        { ...data, unread: 1, id: GroupId + "_" + MessageId },
      ]);
    } else {
      console.log("群消息不连贯，不存储", lastMessage?.MessageId, MessageId);
    }

    await setChatList({ ...data, id: GroupId, Type: 2 }, GroupId);
  } catch (error) {
    console.error("Error handling personal message:", error);
  }
}

// 群通知消息
export async function groupNotificationMessage(data: any) {
  let store = useStore();
  // 如果是群通知消息 则手动赋值MessageId
  data.MessageId = data.Time;
  data.chatId = data.GroupId;
  data.id = data.GroupId;

  // 创建群Cmd=1
  // 加入新成员Cmd=3
  // operation 1增加 2减少成员
  if (data.Cmd == 1 || (data.Cmd == 3 && data.Content.Req.member)) {
    let users: Array<any> = [];
    let member: Array<any> = [];
    if (data.Cmd == 1) {
      users = data.Content.member;
      member = data.Content.member;
    } else if (data.Cmd == 3) {
      users = data.Content.Req.member.user;
      member = data.Content.Group.member;
    }

    const operation =
      data.Cmd === 3 ? data.Content.Req.member.operation : undefined;
    console.log(operation, "---operation");
    if (operation == 2) {
      const messages = await store.db.loadData("chatList", {
        chatId: data.GroupId,
      });
      if (messages.length) {
        member = messages[0]?.Content.Group.member;
        console.log(member, "本地数据");
        console.log(users, "线上本地数据");
      }
    }
    let Text = await generateGroupMessageText(
      data.Cmd,
      users,
      member,
      data.Content,
      operation
    );
    if (Text) {
      await handleGroupMessage({
        ...data,
        Content: {
          ...data.Content,
          Text,
        },
      });
    }
  }
  if (data.Cmd == 3 && data.Content.Group) {
    let Group = data.Content.Group;

    console.log("修改群信息", Group);
    await store.db.updateData("chatList", { chatId: data.chatId }, Group);
  }
}

// 获取群聊消息的最后一条记录
export async function getLastGroupMessage(chatId: string) {
  let store = useStore();

  const singleChatList = await store.db.loadData("groupChat", {
    chatId,
    Grade: 1,
    page: 1,
    limit: 1,
  });
  return singleChatList.length > 0 ? singleChatList[0] : null;
}

// 群聊通知提示信息
export const generateGroupMessageText = async (
  cmd: number,
  users: Array<any>,
  member: Array<any>,
  Content: any,
  operation?: number
) => {
  // 获取所有与 users 对应的 member 中的用户名字
  const userNames = await getInformationFromMember(users, member);

  switch (cmd) {
    case 1: // 创建群聊
      return `${member[0].nick_name}创建了群聊`;

    case 3:
      if (operation === 1) {
        // 邀请加入群聊
        return `${Content.OperateUser.nick_name}邀请了${userNames}加入了群聊`;
      } else if (operation === 2) {
        // 被踢出群聊
        return `${userNames}被${Content.OperateUser.nick_name}踢出了群聊`;
      }
      break;

    default:
      return ""; // 默认返回空字符串
  }
};

// 获取用户的昵称，从 member 数组中提取
export async function getInformationFromMember(
  users: Array<any>,
  member: Array<any>
) {
  const userNames = [];
  console.log(users, "222222");
  console.log(member, "3333");

  // 遍历 users 数组，获取对应的用户信息
  for (let user of users) {
    // 判断 users 中的元素是数字还是对象
    let user_id = typeof user === "number" ? user : user.user_id;

    // 从 member 中找到匹配的用户
    const matchedUser = member.find((m: any) => m.user_id === user_id);

    // 如果找到了匹配的用户，加入到 userNames 数组
    if (matchedUser) {
      userNames.push(matchedUser.nick_name);
    }
  }

  return userNames.join("、");
}
